package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Email;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.ScmService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.core.validator.annotation.Password;


/**
 * 账户设置
 * @author twj
 *
 */
@Service(AccountSafeService.BEAN_NAME)
public class AccountSafeService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.AccountSafeService";
	public static final String NAMESPACE="RS_USER";
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	@Resource(name = RsUserService.BEAN_NAME)
	RsUserService rsUserService;
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;
	@Resource(name = ScmService.BEAN_NAME)
	private ScmService scmService;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject resetLoginPwd(
			@NotBlank(message="用户代码不能为空")
			@RsUser.AnnoUserId
			String userId,
			@MD5(message="新密码未加密")
			String newPwd,
			@MD5(message="旧密码未加密")
			String oldPwd) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(oldPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧密码不能为空");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"新密码不能为空");
		}
		oldPwd = this.versionCompatible(oldPwd);
		newPwd = this.versionCompatible(newPwd);
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		RsUser user = this.one(formMap);
		
		if(user == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		if(!user.getPassword().equals(oldPwd)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧密码输入有误");
		}
		RsUser rsUser = new RsUser();
		rsUser.setPassword(newPwd);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		//同步开店用户到scm系统
    	RsUser tempUser = this.rsUserService.one(userId);
    	//判断当前操作人是否为店长角色
    	if(this.scmService.isSJ(userId)){
    		boolean flag = this.scmService.synDataToScm(tempUser);
    		if(!flag){
    			log.info("#######用户数据到SCM同步失败#########");
    		}else{
    			log.info("#######用户数据到SCM同步成功#########");
    		}
    		
    	}
		
		return executeRerutn(jsonObject);
	}
	/**
	 * 
	 * @param userId
	 * @param email
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject setEmial(
			@RsUser.AnnoUserId
			String userId, 
			@Email(message="邮箱格式非法")
			@RsUser.AnnoEmail
			String email) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(email)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"email地址不能为空");
		}
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		if(!this.exists(formMap)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		RsUser rsUser = new RsUser();
		rsUser.setEmail(email);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
	/**
	 * 绑定手机
	 * @param userId
	 * @param mobile
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Transactional
	public JSONObject setMobile(
			@RsUser.AnnoUserId
			String userId, 
			@Mobile(message="手机号非法")
			String mobile) {
		JSONObject jsonObject = new JSONObject();
		RsUser rsUser = new RsUser();
		Map tempMap = new HashMap();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号不能为空");
		}
		tempMap.put(RsUser.COL_MOBILE, mobile);
		Map formMap = new HashMap();
		formMap.put(RsUser.COL_USER_ID, userId);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR,SqlUtis.EQ)
				);
		RsUser user = this.one(formMap);
		if(user == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户不存在");
		}
		if(!user.getMobile().equals(mobile)){
			SqlUtis.prepareSql(tempMap, "", SqlUtis.getSQL(tempMap, "a."
					+ RsUser.COL_MOBILE, Types.VARCHAR,SqlUtis.EQ)
					);
			if(this.exists(tempMap)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"手机号已存在");
			}
		}
		rsUser.setMobile(mobile);
		formMap.put("rsUser", rsUser);
		int totals = this.update(formMap);
		if(totals != 1){
			return executeRerutnFail(jsonObject);
		}
		return executeRerutn(jsonObject);
	}
	/**
	 * 修改绑定手机
	 * @param userId 用户编码
	 * @param newMobile 新手机号
	 * @param oldMobile 旧手机号
	 * @param tempMobile 临时手机号
	 * @param validateCode 验证码
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject updateMobile(
			@RsUser.AnnoUserId
			String userId, 
			@Mobile(message="新手机号非法")
			String newMobile,
			@Mobile(message="旧手机号非法")
			String oldMobile,
			String tempMobile,
			@Security
			String validateCode) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(userId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if (StringUtils.isBlank(newMobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"新手机不能为空");
		}
		if (StringUtils.isBlank(oldMobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧手机不能为空");
		}
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, newMobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.UPDATE_MOBILE_CODE);
		SqlUtis.prepareSql(tempSmsMap, "", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() == 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码不对！");
		}
		RsUser user = new RsUser();
		Map userMap = new HashMap();
		userMap.put(RsUser.COL_USER_ID, userId);
		user.setMobile(newMobile);
		userMap.put("rsUser", user);
		SqlUtis.prepareSql(userMap, "", SqlUtis.getSQL(userMap, "a."
				+ RsUser.COL_USER_ID, Types.VARCHAR, SqlUtis.EQ));
		int total = this.rsUserService.update(userMap);
		if(total != 1){
			return executeRerutnFail(jsonObject);
		}
		else{
			jsonObject.put("mobile", newMobile);
			return executeRerutn(jsonObject);
		}
	}
	/**
	 * 
	 * @param newMobile 新手机号
	 * @param oldMobile 旧手机号
	 * @param tempMobile 临时手机号
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject sendBeforValidate(
			
			@Mobile(message="新手机号非法")
			String newMobile,
			@Mobile(message="旧手机号非法")
			String oldMobile,
			String tempMobile) {
		JSONObject jsonObject = new JSONObject();
		if (StringUtils.isBlank(newMobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"新手机不能为空");
		}
		if (StringUtils.isBlank(oldMobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧手机不能为空");
		}
		//判断旧手机号是否正确
		if(!oldMobile.equals(tempMobile)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"旧手机不对");
		}
		//当newMobile==oldMobile
		if(newMobile.equals(oldMobile)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"新旧手机号不变");
		}
		Map userMap = new HashMap();
		userMap.put(RsUser.COL_MOBILE, newMobile);
		SqlUtis.prepareSql(userMap, "", SqlUtis.getSQL(userMap, "a."
				+ RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
		boolean flag = this.rsUserService.exists(userMap);
		//newMobile!=oldMobile 并且 newMobile存在
		if((!newMobile.equals(oldMobile)) && flag){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"新手机号已存在");
		}
		//newMobile!=oldMobile 并且 newMobile不存在
		if((!newMobile.equals(oldMobile)) && (!flag)){
			return executeRerutn(jsonObject);
		}
		else{
			return executeRerutnFail(jsonObject);
		}
	}

}
